package managedBean;

import Merlion.CRM.entity.CustomerEntity;
import Merlion.CRM.bean.SalesLeadModuleRemote;
import Merlion.CRM.bean.SalesOrderProcessingModuleRemote;
import Merlion.FRM.entity.CreditProfileEntity;
import Merlion.util.state.CreditProfileState;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import Merlion.FRM.bean.CreditProfileBeanRemote;
import Merlion.util.state.ClientState;
import Merlion.util.state.SalesDocumentState;
import java.util.List;
import javax.faces.application.FacesMessage;
import org.primefaces.event.RowEditEvent;

@ManagedBean(name = "CreditProfileManagedBean")
@ViewScoped
public class CreditProfileManagedBean implements Serializable {

    private Long creditProfileId;
    private Long customerId;
    private String customerGrade;
    private Double creditLimit;
    private Double creditBalance;
    private Double balancePayable;
    private List<String> methodOfPayment;
    private Double paymentAsCIA;
    private String bankName="N/A";
    private String accountNumber="N/A";
    private String creditCardType;
    private String creditCardNumber="0000000000000000";
    private int defaults;
    private String creditProfileStatus;
    
    private CreditProfileState selectedCreditProfile;
    private List<CreditProfileState> selectedCreditProfiles;
    private CreditProfileState[] selectedCreditProfiless;
    
    private CreditProfileState selectedViewCreditProfile;
    
    private List<ClientState> custList;
    private List<SalesDocumentState> salesOrders;
    private boolean editMode;
    private String customerName;
    private String creditCheckStatus;
    private Long salesOrderId;
    
    private CreditProfileEntity cps = new CreditProfileEntity();
    private CustomerEntity cust = new CustomerEntity();
    
    private boolean mode;
    private boolean bankMode;
    
    @EJB
    private CreditProfileBeanRemote creditProfileBean;
    @EJB
    private SalesLeadModuleRemote smb;
    @EJB
    private SalesOrderProcessingModuleRemote sop;
   
    public CreditProfileManagedBean() {
    }

    public void initView(PhaseEvent event) {
        System.out.println("**CreditProfileManagedBean: initView()");
         
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
       
        if (getSelectedCreditProfiles() == null) {
            System.out.println("**CreditProfileManagedBean: Getting list of credit profiles...");
            selectedCreditProfiles = creditProfileBean.viewCreditProfile();
        }
        
        if (getCustList() == null) {
            System.out.println("**CreditProfileManagedBean: Getting list of customers...");
            custList = smb.viewCustomers2();
        }
         if (getSalesOrders() == null) {
            System.out.println("**CreditProfileManagedBean: Getting list of sales orders...");
            salesOrders= sop.viewSalesOrders();
        }
    }
    
    public void initViewDelete(PhaseEvent event) {
        System.out.println("**CreditProfileManagedBean: initViewDelete()");
        
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (getSelectedCreditProfiles() == null) {
            System.out.println("**CreditProfileManagedBean: Getting list of credit profiles...");
            setSelectedCreditProfiles(getCreditProfileBean().viewDeletedCreditProfile());
        }
    }

    public void initViewCreditCheck(PhaseEvent event) {
        System.out.println("**CreditProfileManagedBean: initViewCreditCheck()");
        
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        customerId = (Long) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("customerId");
        customerName = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("customerName");
        creditCheckStatus = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("creditCheckStatus");
        creditBalance = creditProfileBean.getCreditBalance(customerId);
        defaults = creditProfileBean.getDefaults(customerId);
        salesOrders = sop.viewSalesOrders();
        salesOrderId = (Long)FacesContext.getCurrentInstance().getExternalContext().getFlash().get("salesOrderId");
        
    } 
    
    public void doAddCreditProfile(ActionEvent event) {
        try {
            System.out.println("**CreditProfileManagedBean: doAddCreditProfile()");
   
            setCustomerGrade("C");
            setCreditBalance((Double) 1000000.0);
            setBalancePayable((Double) 0.0);
            setPaymentAsCIA((Double) 0.0);
            
            System.out.println(methodOfPayment);
            
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("customerId", getCustomerId());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditLimit", getCreditLimit());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("methodOfPayment", getMethodOfPayment());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("bankName", getBankName());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("accountNumber", getAccountNumber());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditCardType", getCreditCardType());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditCardNumber", getCreditCardNumber());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("customerGrade", getCustomerGrade());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditBalance", getCreditBalance());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("balancePayable", getBalancePayable());
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("paymentAsCIA", getPaymentAsCIA());

            creditProfileId = creditProfileBean.createCreditProfile(getCustomerId(), getCustomerGrade(), getCreditLimit(), getCreditBalance(), getBalancePayable(), getPaymentAsCIA(), getMethodOfPayment(), getBankName(), getAccountNumber(), getCreditCardType(), getCreditCardNumber());
            setCreditProfileId(creditProfileId);
            System.out.println("**CreditProfileManagedBean: Credit profile ID:" + getCreditProfileId());
            
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditProfileId", getCreditProfileId());

            if (getCreditProfileId() != null) {
                System.out.println("**CreditProfileManagedBean: SUCCESSFUL PERSIST.");
                FacesContext.getCurrentInstance().getExternalContext().redirect("SuccessfulAddCreditProfile.xhtml");
            } else {
                System.out.println("**CreditProfileManagedBean: FAIL TO PERSIST.");
                FacesContext.getCurrentInstance().getExternalContext().redirect("FailAddCreditProfile.xhtml");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doDelete(ActionEvent event) {
        System.out.println("**CreditProfileManagedBean: doDelete()");

        try {
            if (getSelectedCreditProfile() != null) {
                setCreditProfileId(getSelectedCreditProfile().getCreditProfileId());
                System.out.println("**CreditProfileManagedBean: Selected credit profile ID:" + getCreditProfileId());
                getCreditProfileBean().deleteCreditProfile(getCreditProfileId());
                System.out.println("**CreditProfileManagedBean: Deletion is successful.");
            } else {
                System.out.println("**CreditProfileManagedBean: Credit profile data is not found.");
            }
            
            FacesContext.getCurrentInstance().getExternalContext().redirect("viewCreditProfile.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //used for multiple deletion
    public void doDeletes(ActionEvent event) {
        System.out.println("**CreditProfileManagedBean: doDeletes()");

        try {
            if (getSelectedCreditProfiless() != null) {
                for (CreditProfileState credit : getSelectedCreditProfiless()) {
                    getCreditProfileBean().deleteCreditProfile(credit.getCreditProfileId());
                }
            } else {
                System.out.println("**CreditProfileManagedBean: Selected credit profiles are null.");
            }
            
            FacesContext.getCurrentInstance().getExternalContext().redirect("viewCreditProfile.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void onEditRow(RowEditEvent event) {
        System.out.println("**CreditProfileManagedBean: onEditRow()");

        try {
            CreditProfileState cp = (CreditProfileState) event.getObject();

            if (cp != null) {
                Long eCreditProfileId = cp.getCreditProfileId();
                Long eCustomerId = cp.getCustomerId();
                String eCustomerGrade = cp.getCustomerGrade();
                Double eCreditLimit = cp.getCreditLimit();
                Double eCreditBalance = cp.getCreditBalance();
                Double eBalancePayable = cp.getBalancePayable();
                Double ePaymentAsCIA = cp.getPaymentAsCIA();          
                String eCreditProfileStatus = cp.getCreditProfileStatus();
                int eDefaults = cp.getDefaults();
                List<String> eMethodOfPayment = cp.getMethodOfPayment();
                String eAccountNumber = cp.getAccountNumber();
                String eBankName = cp.getBankName();
                String eCreditCardType = cp.getCreditCardType();
                String eCreditCardNumber = cp.getCreditCardNumber();

                creditProfileBean.editCreditProfile(eCreditProfileId, eCustomerId, eCustomerGrade, eCreditLimit, eBalancePayable,
                        eCreditBalance, ePaymentAsCIA, eCreditProfileStatus, eDefaults, eMethodOfPayment,
                        eAccountNumber, eBankName, eCreditCardType, eCreditCardNumber);
                System.out.println("**CreditProfileManagedBean :  Credit Profile is successfully edited.");
            } else {
                System.out.println("**CreditProfileManagedBean: No credit profile data found. onEditRow() failed.");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void onEditDialog(ActionEvent event) {
        System.out.println("**CreditProfileManagedBean : onEditDialog()");

        try {
            Long eCreditProfileId = getSelectedViewCreditProfile().getCreditProfileId();
            Long eCustomerId = getSelectedViewCreditProfile().getCustomerId();
            String eCustomerGrade = getSelectedViewCreditProfile().getCustomerGrade();
            Double eCreditLimit = getSelectedViewCreditProfile().getCreditLimit();
            Double eCreditBalance = getSelectedViewCreditProfile().getCreditBalance();
            Double eBalancePayable = getSelectedViewCreditProfile().getBalancePayable();
            Double ePaymentAsCIA = getSelectedViewCreditProfile().getPaymentAsCIA();
            String eCreditProfileStatus = getSelectedViewCreditProfile().getCreditProfileStatus();
            int eDefaults = getSelectedViewCreditProfile().getDefaults();
            List<String> eMethodOfPayment = getSelectedViewCreditProfile().getMethodOfPayment();
            String eAccountNumber = getSelectedViewCreditProfile().getAccountNumber();
            String eBankName = getSelectedViewCreditProfile().getBankName();
            String eCreditCardType = getSelectedViewCreditProfile().getCreditCardType();
            String eCreditCardNumber = getSelectedViewCreditProfile().getCreditCardNumber();
            
            creditProfileBean.editCreditProfile(eCreditProfileId, eCustomerId, eCustomerGrade, eCreditLimit, eBalancePayable,
                        eCreditBalance, ePaymentAsCIA, eCreditProfileStatus, eDefaults, eMethodOfPayment,
                        eAccountNumber, eBankName, eCreditCardType, eCreditCardNumber);
            System.out.println("**CreditProfileManagedBean :  Credit Profile is successfully edited.");
            
            FacesContext.getCurrentInstance().getExternalContext().redirect("viewCreditProfile.xhtml");
            
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void doValidateCreditProfile(ActionEvent event) {
        System.out.println("**CreditProfileManagedBean: doValidateCreditProfile()");

        try {
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditProfileId", getCreditProfileId());
            getCreditProfileBean().validateCreditProfile(getCreditProfileId());
            System.out.println("**CreditProfileManagedBean: Credit profile is successfully validated.");
            FacesContext.getCurrentInstance().getExternalContext().redirect("viewCreditProfile.xhtml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void doPerformCreditCheck(ActionEvent event) {
        System.out.println("**CreditProfileManagedBean: doSearchCreditProfile()");
        
        try {
            customerName = creditProfileBean.getCustomerName(customerId);
           
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("customerName", customerName); 
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("customerId", customerId);   
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("salesOrderId", salesOrderId);   
            
            boolean status = creditProfileBean.overallCreditCheck(customerId, salesOrderId);
            if (status == true) {
                creditCheckStatus = "Approved";
            } else {
                creditCheckStatus = "Denied";
            }
            
            System.out.println("Calling credit profile bean.");
            System.out.println("Generate email to inform sales department.");
            creditProfileBean.sendResultForCreditCheck(salesOrderId, customerId, status);
            
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("creditCheckStatus", creditCheckStatus);
            FacesContext.getCurrentInstance().getExternalContext().redirect("CreditCheck2.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
   
    public void doHandleMethod(){
        System.out.println("**Do Handle Method");
        for(String o: methodOfPayment){
            String p = o;
            if(p.equals("Credit Card")){
                this.setMode(true);
            }
            if(p.equals("GIRO")){
                this.setBankMode(true);
            }
         }
    }
    
    
    public Long getCreditProfileId() {
        return creditProfileId;
    }

    public void setCreditProfileId(Long creditProfileId) {
        this.creditProfileId = creditProfileId;
    }

    public Long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Long customerId) {
        this.customerId = customerId;
    }

    public String getCustomerGrade() {
        return customerGrade;
    }

    public void setCustomerGrade(String customerGrade) {
        this.customerGrade = customerGrade;
    }

    public Double getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(Double creditLimit) {
        this.creditLimit = creditLimit;
    }

    public Double getCreditBalance() {
        return creditBalance;
    }

    public void setCreditBalance(Double creditBalance) {
        this.creditBalance = creditBalance;
    }

    public Double getBalancePayable() {
        return balancePayable;
    }

    public void setBalancePayable(Double balancePayable) {
        this.balancePayable = balancePayable;
    }

    public List<String> getMethodOfPayment() {
        return methodOfPayment;
    }

    public void setMethodOfPayment(List<String> methodOfPayment) {
        this.methodOfPayment = methodOfPayment;
    }

    public Double getPaymentAsCIA() {
        return paymentAsCIA;
    }

    public void setPaymentAsCIA(Double paymentAsCIA) {
        this.paymentAsCIA = paymentAsCIA;
    }

    public String getBankName() {
        return bankName;
    }

    public void setBankName(String bankName) {
        this.bankName = bankName;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public String getCreditCardType() {
        return creditCardType;
    }

    public void setCreditCardType(String creditCardType) {
        this.creditCardType = creditCardType;
    }

    public String getCreditCardNumber() {
        return creditCardNumber;
    }

    public void setCreditCardNumber(String creditCardNumber) {
        this.creditCardNumber = creditCardNumber;
    }

    public int getDefaults() {
        return defaults;
    }

    public void setDefaults(int defaults) {
        this.defaults = defaults;
    }

    public String getCreditProfileStatus() {
        return creditProfileStatus;
    }

    public void setCreditProfileStatus(String creditProfileStatus) {
        this.creditProfileStatus = creditProfileStatus;
    }

    public CreditProfileState getSelectedCreditProfile() {
        return selectedCreditProfile;
    }

    public void setSelectedCreditProfile(CreditProfileState selectedCreditProfile) {
        this.selectedCreditProfile = selectedCreditProfile;
    }

    public List<CreditProfileState> getSelectedCreditProfiles() {
        return selectedCreditProfiles;
    }

    public void setSelectedCreditProfiles(List<CreditProfileState> selectedCreditProfiles) {
        this.selectedCreditProfiles = selectedCreditProfiles;
    }

    public CreditProfileState[] getSelectedCreditProfiless() {
        return selectedCreditProfiless;
    }

    public void setSelectedCreditProfiless(CreditProfileState[] selectedCreditProfiless) {
        this.selectedCreditProfiless = selectedCreditProfiless;
    }

    public CreditProfileState getSelectedViewCreditProfile() {
        return selectedViewCreditProfile;
    }

    public void setSelectedViewCreditProfile(CreditProfileState selectedViewCreditProfile) {
        this.selectedViewCreditProfile = selectedViewCreditProfile;
    }

    public List<ClientState> getCustList() {
        return custList;
    }

    public void setCustList(List<ClientState> custList) {
        this.custList = custList;
    }

    public String getCustomerName() {
        System.out.println("GET CUSTOMER NAME");
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCreditCheckStatus() {
        return creditCheckStatus;
    }

    public void setCreditCheckStatus(String creditCheckStatus) {
        this.creditCheckStatus = creditCheckStatus;
    }

    public CreditProfileEntity getCps() {
        return cps;
    }

    public void setCps(CreditProfileEntity cps) {
        this.cps = cps;
    }

    public CustomerEntity getCust() {
        return cust;
    }

    public void setCust(CustomerEntity cust) {
        this.cust = cust;
    }

    public CreditProfileBeanRemote getCreditProfileBean() {
        return creditProfileBean;
    }

    public void setCreditProfileBean(CreditProfileBeanRemote creditProfileBean) {
        this.creditProfileBean = creditProfileBean;
    }

    public SalesLeadModuleRemote getSmb() {
        return smb;
    }

    public void setSmb(SalesLeadModuleRemote smb) {
        this.smb = smb;
    }

    public SalesOrderProcessingModuleRemote getSop() {
        return sop;
    }

    public void setSop(SalesOrderProcessingModuleRemote sop) {
        this.sop = sop;
    }

    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }

    public Long getSalesOrderId() {
        return salesOrderId;
    }

    public void setSalesOrderId(Long salesOrderId) {
        this.salesOrderId = salesOrderId;
    }

    public List<SalesDocumentState> getSalesOrders() {
        return salesOrders;
    }

    public void setSalesOrders(List<SalesDocumentState> salesOrders) {
        this.salesOrders = salesOrders;
    }

    public void getCompanyNames(ActionEvent event){
        System.out.println("**CreditProfileBean: GET COMPANY NAME()");
        customerId =selectedViewCreditProfile.getCustomerId();
        //System.out.println("**CreditProfileBean: CustomerID "+customerId);
        customerName = creditProfileBean.getCustomerName(customerId);
        this.setCustomerName(customerName);
        //System.out.println("**CreditProfileBean: CUSTOMER NAME :" + customerName);
   
    }

    public boolean isMode() {
        return mode;
    }

    public void setMode(boolean mode) {
        this.mode = mode;
    }

    public boolean isBankMode() {
        return bankMode;
    }

    public void setBankMode(boolean bankMode) {
        this.bankMode = bankMode;
    }
}
